package com.thinkingcoder.tcgateway.config;

import java.util.Properties;

import com.thinkingcoder.tcgateway.properties.GatewayProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;

import com.thinkingcoder.tcrpc.core.registry.RegistryCenter;
import com.thinkingcoder.tcrpc.core.registry.tc.TcRegistryCenter;

import lombok.extern.slf4j.Slf4j;

/**
 * gateway config.
 */
@Slf4j
@Configuration
public class GatewayConfig {

    @Bean
    public RegistryCenter registryCenter() {
        return new TcRegistryCenter();
    }

    /**
     * 将自定义的 WebHandler 加入到 SimpleUrlHandlerMapping 中
     *
     */
    @Bean
    ApplicationRunner tcGatewayRunner(@Autowired ApplicationContext ctx,
        @Autowired GatewayProperties gatewayProperties) {
        return args -> {
            SimpleUrlHandlerMapping simpleUrlHandlerMapping = ctx.getBean(SimpleUrlHandlerMapping.class);
            Properties mappings = new Properties();
            mappings.put(gatewayProperties.getGatewayPrefix() + "/**", "gatewayWebHandler");
            simpleUrlHandlerMapping.setMappings(mappings);
            simpleUrlHandlerMapping.initApplicationContext();
            log.info("TC-Gateway started successfully. {}", simpleUrlHandlerMapping.getUrlMap());
        };
    }

}
